package database

func ListGroupIdByUserId(userId int64) (*[]int64, error) {
	var groupIds []int64

	// 查询所有包含该用户的组
	if err := db.Model(&UserGroup{}).Where("user_id = ?", userId).Pluck("group_id", &groupIds).Error; err != nil {
		return nil, err
	}

	return &groupIds, nil
}

func GetUserGroupByUidAndGid(userId int64, groupId int64) (*UserGroup, error) {
	var userGroup *UserGroup
	err := db.Model(&UserGroup{}).Where("user_id = ? and group_id = ? ", userId, groupId).First(&userGroup).Error

	return userGroup, err
}

func GetGroupByID(id int64) (*Group, error) {
	group := &Group{}
	err := db.First(group, id).Error
	return group, err
}

func ListCustomGroupByUserId(userId int64) ([]*Group, error) {
	var groupList []*Group

	err := db.Model(&Group{}).
		Joins("INNER JOIN user_group ON user_group.group_id = groups.id").
		Where("user_group.user_id = ?", userId).Where("groups.type=?", 0).Scan(&groupList).Error

	return groupList, err
}

func DeleteUserGroup(userId int64, groupId int64) error {
	err := db.Where("user_id=? and group_id = ?", userId, groupId).Delete(&UserGroup{}).Error
	return err
}
